package com.qding.cupms.admin.rest.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import com.qding.cupms.admin.rest.client.ClientHelper;
import com.qding.cupms.admin.rest.redis.SessionRedisTemplate;
import com.qding.cupms.common.constant.Constant;

/**
 * 访问控制
 * 
 * @since [产品/模块版本]
 * @author ly
 * @version v1.0 Date:2017年8月10日 下午3:19:15
 */
public class ShiroPermissionFilter extends AuthorizationFilter {

    private final static Logger logger = Logger.getLogger(ShiroPermissionFilter.class);

    /**
     * sessionRedisTemplate 会话redis
     */
    @Autowired
    private SessionRedisTemplate sessionRedisTemplate;

    /**
     * 访问控制
     * 
     * @param request
     * @param response
     * @param mappedValue
     * @return true 继续访问 false 中断访问
     * @throws Exception
     * @author ly Date:2017年8月11日 下午2:01:15
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(Constant.HEADER_TOKEN_NAME);
        if (StringUtils.isBlank(token)) {
            // token 为空
            ClientHelper.writeNologinResponse(response);// 返回未登录报文
            return false;
        }
        DefaultSessionKey sessionKey = new DefaultSessionKey(token);
        Session session = SecurityUtils.getSecurityManager().getSession(sessionKey);

        if (session == null || session.getAttribute(Constant.GLOBAL_SESSION_USER_KEY) == null) {
            ClientHelper.writeNologinResponse(response);// 返回未登录报文
            return false;
        }
        //更新会话时间
        session.touch();
        return true;

    }
}
